#!/usr/bin/python2.7

import argparse

def decode(data, keychar, offset=0):
    maxlen = len(data)
    decoded = bytearray()
    for i in range(offset, maxlen):
        dec = data[i] ^ keychar
        decoded.append(dec)
    return decoded

def save_decoded(decdata, outfile):
    fr = open(outfile, "wb")
    if fr is None:
        return False
    for a in decdata:
        fr.write('%c' % a)
    fr.close()
    return True

def main():
    parser = argparse.ArgumentParser(description="Kronos beacon decoder")
    parser.add_argument('--datafile', dest="file", default=None, help="Input file: captured Kronos beacon", required=True)
    parser.add_argument('--outfile', dest="outfile", default="out.bin", help="Output file")
    args = parser.parse_args()


    data = bytearray(open(args.file, 'rb').read())
    key = data[0]
    decdata = decode(data[1:], key)
    save_decoded(decdata, args.outfile)

    print "Saved to: "+ args.outfile


if __name__ == "__main__":
    main()
